import { Account } from './../entity/account.entity';
import { LoginError } from './../filter/error.filter';
// 登录的本质 使用明文的用户名密码  换取一个暗文的用户名信息的token
//  zhangsan001  123456   =》 token : xxxxzhangsan001yyyy
//  xxxxzhangsan001yyyy   =》 token verify

import { IMiddleware, Middleware } from '@midwayjs/core';
import { Context, NextFunction } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';

/*
本拦截器 作用于 尽可能多的controller ，需求访问者 必须header携带
authorization: xxxx=zhangsan001=yyyy 用于表明身份
如果没有携带，则不允许访问，如果携带的格式不正确，也不允许访问
*/
@Middleware()
export class AuthInterceptorMiddleware
  implements IMiddleware<Context, NextFunction>
{
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (!ctx.headers.authorization) {
        throw new LoginError('无用户信息，请登录');
      }
      const auth = ctx.headers.authorization;
      const results = auth.split('=');
      console.log(results);
      if (results.length !== 3) {
        throw new LoginError('用户信息不合法，请登录');
      }
      const username = results[1];
      console.log('当前登录人: ' + username);
      ctx.setAttr('username', username);
      const result = await next();
      return result;
    };
  }
}
// 模拟登录接口
@Middleware()
export class LoginMiddleware implements IMiddleware<Context, NextFunction> {
  @InjectEntityModel(Account)
  repo: Repository<Account>;
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (ctx.path === '/login') {
        const r: any = ctx.request.body;
        const username = r.username;
        const password1 = r.password;
        const account = await this.repo.findOneBy({ username: username });
        console.log('Account :' + account);
        if (!account) {
          throw new LoginError('用户名密码不存在');
        }
        if (!account.enabled) {
          throw new LoginError('用户被冻结');
        }
        const password2 = account.password;
        if (password1 !== password2) {
          throw new LoginError('用户名密码不匹配');
        }
        return {
          token: `xxxx=${account.username}=yyyy`,
          account: account,
        };
      } else {
        const result = await next();
        return result;
      }
    };
  }
}
// 方便开发过程中swagger可以不登录就测试 模拟当前登录人叫swagger
@Middleware()
export class SwaggerMiddleware implements IMiddleware<Context, NextFunction> {
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      if (!ctx.headers.authorization) {
        ctx.headers.authorization = 'xxxx=swagger=yyyy';
      }
      const result = await next();
      return result;
    };
  }
}
